<template>
  <div class="card">
    <el-form label-width="auto" label-position="top">
      <el-form-item label="用户名">
        <el-input v-model="username" :disabled="!!id" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" v-if="!id">
        <el-input v-model="password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="角色">
        <el-select-v2 v-model="rs" :options="roles" :size="size" multiple filterable />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="desc" type="textarea" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { getUser, updUser, addUser, getRoles } from '@/http'
import { useTabStore } from '@/stores'
import { useRoute } from 'vue-router'

const { size } = inject('app_size')

const route = useRoute()
const tabStore = useTabStore()
const username = ref('')
const password = ref('')
const desc = ref('')
const rs = ref([])
const roles = ref([])

const { id } = route.params

onMounted(async () => {
  if (id) {
    const result = await getUser(id)
    username.value = result.username
    desc.value = result.description
    rs.value = result.roles.map((p) => p.id)
  }
})

onMounted(async () => {
  const result = await getRoles({
    page: 1,
    limit: 9999,
    // search_code: search.value,
    // search_description: search.value,
    sort_created_at: 'desc'
  })
  roles.value = result.data.map((role) => ({
    value: role.id,
    label: role.code
  }))
})

const onSubmit = async () => {
  let result

  const data = {
    description: desc.value,
    roles: rs.value
  }

  if (id) {
    result = await updUser(id, data)
  } else {
    result = await addUser({
      username: username.value,
      password: password.value,
      ...data
    })
  }

  if (result) {
    tabStore.removeTab(id ? 'user-save' : 'user-add')
  }
}

const onCancel = () => {
  tabStore.removeTab(id ? 'user-save' : 'user-add')
}
</script>

<style lang="scss" scoped>
.el-form {
  max-width: 600px;
}
</style>
